#!/bin/sh

PREFIX=
. "$PREFIX/lib/libalpine.sh"

conf="$ROOT/etc/conf.d/qos"

cfgval() {
	awk -F= "/^$1/ {print \$2}" $conf 2>/dev/null
}

setcfg() {
	local key=$1
	local value=$2
	sed -i "s/^\\(\\#\\)*$key=.*/$key=$value/" "$conf"
	if ! grep "^$key=" "$conf" >/dev/null ; then
		echo "$key=$value" >> "$conf"
	fi
}

apk_add iproute2

if [ -f "$conf" ] ; then
	_UPLINK_RATE=$(cfgval UPLINK_RATE)
	_DOWNLINK_RATE=$(cfgval DOWNLINK_RATE)
	_RATE_SUB_PERCENT=$(cfgval RATE_SUB_PERCENT)
else
	echo "Configuration file '$conf' not found"
	exit 1
fi

echo "**********************************************************************"
echo "Since ISPs tend to overestimate the speeds they offer, it would probably be best"
echo " if you measure this on a free line to set values very precisely."
echo "**********************************************************************"
echo
echon "Specify the upload speed of your internet connection (mbps, mbit, kbit, kbps, bps): [$_UPLINK_RATE] "
	default_read _UPLINK_RATE $_UPLINK_RATE
echo
echon "Specify the download speed of your internet connection (mbps, mbit, kbit, kbps, bps): [$_DOWNLINK_RATE] "
	default_read _DOWNLINK_RATE $_DOWNLINK_RATE
echo
echo "**********************************************************************"
echo "In order to prevent traffic queuing at the ISP side or in your modem,"
echo " you should set a slightly lower rate than real one."
echo "This way the bottleneck is the router,"
echo " not the ISP or modem, which allows to control the queue."
echo "**********************************************************************"
echo
echon "Specify amount of percents: [$_RATE_SUB_PERCENT] "
	default_read _RATE_SUB_PERCENT $_RATE_SUB_PERCENT

echon "Start QoS? (y/n) [y] "
	default_read startqos "y"
		case "$startqos" in
			[Yy]*) /etc/init.d/qos start;;
		esac

echon "Make QoS to be started on boot? (y/n) [y] "
	default_read bootstartqos "y"
		case "$bootstartqos" in
			[Yy]*) rc_add qos;;
		esac

setcfg UPLINK_RATE $_UPLINK_RATE
setcfg DOWNLINK_RATE $_DOWNLINK_RATE
setcfg RATE_SUB_PERCENT $_RATE_SUB_PERCENT
